package org.hugh.space.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hugh.space.business.CurrentUser;

public class AuthenticationFilter extends AbstractFilter implements Filter {

	public static final String ORIGINAL_VIEW_KEY = "originalViewKey";
	public static final String LOGIN_VIEW = "/login.jsp";
	public static final String RESTRICT_URL =  "/file";
	public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";
	private static final Log logger = LogFactory.getLog(AuthenticationFilter.class);
	


	public AuthenticationFilter() {
		super();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
		if(request.getAttribute(alreadyFilteredAttributeName) != null){
			chain.doFilter(request, response);
			return;
        } 
            
		request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
        
		HttpSession session = httpRequest.getSession();
		String url = httpRequest.getServletPath();
		if (!isLoggedIn(httpRequest)) {
			CurrentUser.setInstance(null);
			if (url.startsWith(RESTRICT_URL)) {
				session.setAttribute(ORIGINAL_VIEW_KEY, httpRequest.getRequestURI());
				httpResponse.sendRedirect(httpRequest.getContextPath()+ LOGIN_VIEW);
				return;
			} 
		}
		chain.doFilter(request, response);
	}

	private boolean isLoggedIn(final HttpServletRequest request) {
		return getBusiness().getUserPreferences(request).isLoggedIn();
	}

	protected String getAlreadyFilteredAttributeName() {
		String name = getClass().getName();
		return name + ".FILTERED";
	}

}